﻿using System;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Windows.Forms;
using System.IO;
using TpData.Manager;
using TpBaseObjects.Objects;


namespace TpOlMailAddIn {
    public partial class ThisAddIn {

        //private Logger log;
        private TecUserObj u;
        private const string logArea = "TpOlMailAddIn.ThisAddIn";
        private const string errType = "Err";
        private const string logType = "Log";

        private void ThisAddIn_Startup(object sender, System.EventArgs e) {
            //this.log = new Logger();
            u = TecUserDataManager.LoadTecUser(Environment.UserName);
            Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(SaveMailItem);

        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e) {
            
        }

        private void SaveMailItem(object Item, ref bool Cancel) {

            if (Item is Outlook.MailItem) {
                Outlook.MailItem mail = (Outlook.MailItem)Item;
                if (mail.TaskSubject == null) {
                    return;
                }
                string fileName = mail.TaskSubject;
                if (fileName != null) {
                    LogDataManager.SaveLog(u.UserID, logType, logArea, "SaveMailItem: " + fileName, false);
                    if (fileName != null && fileName.Length > 0) {
                        if (File.Exists(fileName)) {
                            File.Delete(fileName);
                        }
                        //Save the mail in .msg format
                        //
                        try {
                            if (fileName.IndexOf(":") > 0) {
                                mail.SaveAs(fileName, Outlook.OlSaveAsType.olMSG);
                                LogDataManager.SaveLog(u.UserID, logType, logArea, "SaveMailItem: File is saved! (" + fileName +")" , false);
                            }
                        } catch (Exception ex) {
                            LogDataManager.SaveLog(u.UserID, errType, logArea, "SaveMailItem: " + ex.Message, true);
                        }

                    }
                } else {
                    LogDataManager.SaveLog(u.UserID, errType, logArea, "SaveMailItem: fileName is null)", false);
                }
                
            }

        }

        #region Von VSTO generierter Code

        /// <summary>
        /// Erforderliche Methode für die Designerunterstützung.
        /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
        /// </summary>
        private void InternalStartup() {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
